﻿<script lang="ts" setup name="storeOutbound">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { useStoreMaterialsApi } from '/@/api/store/storeMaterials';
import { useStoreOutboundApi } from '/@/api/store/storeOutbound';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

// 组件导入
import StoreTypeTree from '/@/views/store/storeMaterials/component/storeTypeTree.vue';
import CartManager from '/@/views/store/components/CartManager.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from '/@/components/table/importData.vue';
import { useUserInfo } from '/@/stores/userInfo';

const storeMaterialsApi = useStoreMaterialsApi();
const storeOutboundApi = useStoreOutboundApi();
const printDialogRef = ref();
const cartManagerRef = ref();
const importDataRef = ref();
const storeTypeTreeRef = ref();
const userInfo = useUserInfo();

const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as any[],
	storeTypeTreeData: [] as any[], // 物资分类树数据
	currentCategoryId: 0, // 当前选中的分类ID，0表示全部
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime',
		order: 'descending',
		descStr: 'descending',
	},
	tableData: [],
	cartItems: [] as any[], // 购物车物品
});

// 页面加载时
onMounted(async () => {
	await loadStoreTypeTree();
	await handleQuery();
});

// 加载物资分类树数据
const loadStoreTypeTree = async () => {
	try {
		const data = (await storeMaterialsApi.getDropdownData(true).then((res) => res.data.result)) ?? {};
		console.log('API返回数据:', data);
		state.dropdownData.storeTypeId = data.pid || [];
		state.storeTypeTreeData = data.pid || [];
		console.log('树数据:', state.storeTypeTreeData);
	} catch (error) {
		console.error('加载物资分类树失败:', error);
		ElMessage.error('加载物资分类失败');
	}
};

// 分类节点点击事件
const handleCategoryChange = (node: any) => {
	const nodeId = node.id || node.value || 0;
	state.currentCategoryId = nodeId;
	state.tableParams.page = 1;
	if (nodeId === 0 || nodeId === '0') {
		delete state.tableQueryParams.storeTypeId;
	} else {
		state.tableQueryParams.storeTypeId = nodeId;
	}
	handleQuery();
};

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	try {
		state.tableParams = Object.assign(state.tableParams, params);
		const queryParams = Object.assign({}, state.tableQueryParams, state.tableParams);
		const result = await storeMaterialsApi.page(queryParams).then((res) => res.data.result);
		state.tableParams.total = result?.total;
		state.tableData = result?.items ?? [];
	} catch (error) {
		console.error('查询失败:', error);
		ElMessage.error('查询失败');
	} finally {
		state.tableLoading = false;
	}
};

// 重置查询
const resetQuery = () => {
	state.tableQueryParams = {};
	state.currentCategoryId = 0;
	nextTick(() => {
		storeTypeTreeRef.value?.setCurrentKey(0);
	});
	handleQuery();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	state.tableParams.page = 1;
	handleQuery();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 加入购物车
const addToCart = (row: any) => {
	// 检查是否已存在
	const existingIndex = state.cartItems.findIndex((item) => item.id === row.id);
	if (existingIndex !== -1) {
		ElMessage.warning('该物资已在购物车中');
		return;
	}

	// 检查库存
	if (row.availableStock <= 0) {
		ElMessage.warning('该物资库存不足');
		return;
	}

	// 添加到购物车
	const cartItem = {
		...row,
		requestQuantity: 1, // 默认申请数量为1
		remark: '',
	};

	state.cartItems.push(cartItem);
	ElMessage.success(`已将"${row.name}"添加到购物车`);
};

// 打开购物车
const openCart = () => {
	cartManagerRef.value?.openCart();
};

// 移除购物车物品
const removeFromCart = (index: number) => {
	state.cartItems.splice(index, 1);
	ElMessage.success('已移除物品');
};

// 清空购物车
const clearCart = () => {
	state.cartItems = [];
	ElMessage.success('购物车已清空');
};

// 生成申请号
const generateRequestNo = () => {
	const now = new Date();
	const dateTimeStr = now.toISOString().slice(0, 19).replace(/[-:T]/g, '').slice(0, 14);
	return `OUT${dateTimeStr}`;
};

// 生成批次号
const generateBatchNo = () => {
	const now = new Date();
	const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '');
	const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '');
	return `BATCH_${dateStr}_${timeStr}`;
};

// 提交购物车
const submitCart = async (items: any[], form?: any) => {
	try {
		// 检查是否有用户信息
		if (!userInfo.userInfos?.id) {
			ElMessage.error('获取用户信息失败，请重新登录');
			return;
		}
		// 验证必要参数
		if (!items || items.length === 0) {
			ElMessage.warning('购物车为空');
			return;
		}

		console.log('购物车提交参数:', { items, form });

		// 构建出库申请数据
		const batchNo = generateBatchNo();
		const requestTime = new Date().toISOString().slice(0, 19).replace('T', ' ');

		const requests = items.map((item, index) => ({
			batchNo: batchNo,
			requestNo: generateRequestNo(),
			storeTypeId: item.storeTypeId,
			storeTypeName: item.storeTypeDisplayName,
			materialId: item.id,
			materialName: item.name,
			materialPrice: item.price,
			quantity: item.requestQuantity,
			unit: item.unit,
			materialPriceTotal: item.price * item.requestQuantity,
			applicantId: userInfo.userInfos.id,
			applicantName: userInfo.userInfos.realName || userInfo.userInfos.name,
			applicantDept: userInfo.userInfos.orgName || '',
			receiverId: item.receiverId,
			receiverName: item.receiverName,
			receiverDept: item.receiverDept,
			requestTime: new Date(),
			expectedDate: item.expectedDate,
			statusNewOrChange: item.statusNewOrChange || 2, // 物资状态：新增/更新
			remark: item.remark || '',
			approvalAction: 1, // 审批状态：待审核(Pending)
			confirmerId: form?.confirmerId || userInfo.userInfos.managerUserId, // 优先使用表单选择的确认人，fallback到直属主管
			confirmerName: form?.confirmerName || '', // 确认人名称
		}));

		// 调用后端API提交出库申请
		console.log('提交出库申请:', requests);

		// 逐个提交申请（因为后端没有批量添加接口）
		for (const request of requests) {
			await storeOutboundApi.add(request);
		}

		ElMessage.success(`成功提交 ${items.length} 项出库申请`);
		cartManagerRef.value?.resetSubmitting();
		cartManagerRef.value?.handleClose();
		cartManagerRef.value?.resetForm();
		state.cartItems = [];
	} catch (error) {
		console.error('提交失败:', error);
		ElMessage.error('提交失败');
		cartManagerRef.value?.resetSubmitting();
	}
};

// 导出数据
const exportStoreMaterialsCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		let params;
		if (command === 'select') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
		} else if (command === 'current') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams);
		} else if (command === 'all') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
		}
		await storeMaterialsApi.exportData(params).then((res) => downloadStreamFile(res));
	} finally {
		state.exportLoading = false;
	}
};
</script>
<template>
	<div class="store-outbound-container" v-loading="state.exportLoading">
		<splitpanes class="default-theme">
			<!-- 左侧物资分类树 -->
			<pane size="15">
				<StoreTypeTree ref="storeTypeTreeRef" :data="state.storeTypeTreeData" @node-click="handleCategoryChange" @refresh="loadStoreTypeTree" />
			</pane>

			<!-- 右侧物资信息表格 -->
			<pane size="80" style="overflow: auto">
				<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
					<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
						<el-row>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item label="关键字">
									<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="物资名称">
									<el-input v-model="state.tableQueryParams.name" clearable placeholder="请输入物资名称" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="状态">
									<g-sys-dict v-model="state.tableQueryParams.status" code="StatusEnum" render-as="select" placeholder="请选择状态" clearable filterable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
								<el-form-item label="库存状态">
									<g-sys-dict v-model="state.tableQueryParams.stockStatus" code="StockStatusEnum" render-as="select" placeholder="请选择库存状态" clearable filterable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
								<el-form-item>
									<el-button-group style="display: flex; align-items: center">
										<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'storeMaterials:page'" v-reclick="1000"> 查询 </el-button>
										<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
										<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
										<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
										<el-button type="success" style="margin-left: 5px" icon="ele-ShoppingCart" @click="openCart" :disabled="state.cartItems.length === 0">
											购物车 ({{ state.cartItems.length }})
										</el-button>
										<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportStoreMaterialsCommand">
											<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'storeMaterials:export'"> 导出 </el-button>
											<template #dropdown>
												<el-dropdown-menu>
													<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
													<el-dropdown-item command="current">导出本页</el-dropdown-item>
													<el-dropdown-item command="all">导出全部</el-dropdown-item>
												</el-dropdown-menu>
											</template>
										</el-dropdown>
									</el-button-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-card>

				<el-card class="full-table" shadow="hover" style="margin-top: 5px">
					<el-table
						:data="state.tableData"
						@selection-change="
							(val: any[]) => {
								state.selectData = val;
							}
						"
						style="width: 100%"
						v-loading="state.tableLoading"
						tooltip-effect="light"
						row-key="id"
						@sort-change="sortChange"
						border
					>
						<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('storeMaterials:export')" />
						<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
						<el-table-column prop="storeTypeId" label="分类" width="150" fixed="left" :formatter="(row: any) => row.storeTypeDisplayName" show-overflow-tooltip />
						<el-table-column prop="name" label="物资名称" width="200" fixed="left" show-overflow-tooltip />
						<el-table-column prop="unit" label="单位" show-overflow-tooltip />
						<el-table-column prop="price" label="单价" show-overflow-tooltip />
						<el-table-column prop="minStock" label="最小库存" show-overflow-tooltip />
						<el-table-column prop="maxStock" label="最大库存" show-overflow-tooltip />
						<el-table-column prop="orderNo" label="排序" sortable="custom" show-overflow-tooltip />
						<el-table-column prop="status" label="状态" show-overflow-tooltip>
							<template #default="scope">
								<g-sys-dict v-model="scope.row.status" code="StatusEnum" />
							</template>
						</el-table-column>
						<el-table-column prop="currentStock" label="库存数量" show-overflow-tooltip />
						<el-table-column prop="availableStock" label="可用库存" fixed="left" show-overflow-tooltip />
						<el-table-column prop="reservedStock" label="申请库存" show-overflow-tooltip />
						<el-table-column prop="inTransitStock" label="入库库存" show-overflow-tooltip />
						<el-table-column prop="stockStatus" label="库存状态" fixed="left" show-overflow-tooltip>
							<template #default="scope">
								<g-sys-dict v-model="scope.row.stockStatus" code="StockStatusEnum" />
							</template>
						</el-table-column>
						<el-table-column prop="lastStockUpdateTime" label="更新时间" show-overflow-tooltip />
						<el-table-column prop="remark" label="备注" show-overflow-tooltip />
						<el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
							<template #default="scope">
								<ModifyRecord :data="scope.row" />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip>
							<template #default="scope">
								<el-button icon="ele-ShoppingCart" size="small" text type="primary" @click="addToCart(scope.row)" :disabled="scope.row.availableStock <= 0"> 加入购物车 </el-button>
							</template>
						</el-table-column>
					</el-table>

					<el-pagination
						v-model:currentPage="state.tableParams.page"
						v-model:page-size="state.tableParams.pageSize"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="[10, 20, 50, 100, 200, 500]"
						:total="state.tableParams.total"
						size="small"
						background
					/>
				</el-card>
			</pane>
		</splitpanes>

		<!-- 购物车组件 -->
		<CartManager ref="cartManagerRef" cart-type="outbound" :cart-items="state.cartItems" @submit-cart="submitCart" @remove-item="removeFromCart" @clear-cart="clearCart" @close="() => {}" />

		<!-- 对话框组件 -->
		<ImportData ref="importDataRef" :import="storeMaterialsApi.importData" :download="storeMaterialsApi.downloadTemplate" v-auth="'storeMaterials:import'" @refresh="handleQuery" />
		<printDialog ref="printDialogRef" :title="'打印物资信息表'" @reloadTable="handleQuery" />
	</div>
</template>
<style scoped>
.store-outbound-container {
	height: calc(100vh - 84px);
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

:deep(.splitpanes__pane) {
	overflow: hidden;
}

:deep(.splitpanes__splitter) {
	background-color: var(--el-border-color-light);
	position: relative;
	opacity: 0.7;
}

:deep(.splitpanes__splitter:hover) {
	opacity: 1;
	background-color: var(--el-color-primary);
}
</style>
